//
//  KSSingleSelectUtil.swift
//  Slaughter
//
//  Created by Ken on 2019/8/6.
//  Copyright © 2019 zwb. All rights reserved.
//

import UIKit

struct nameAndModel<T> {
    var shows:[String]
    var model:T
}
public struct idAndName {
    var name:String
    var id:String
}

enum KSSelectType {
    /// needConfirm - 单选需要二次确认,  unNeedConfirm - 不需要二次确认， onlyShow - 不需要选择单纯展示
    case needConfirm,
         unNeedConfirm,
         onlyShow
}
 
// 数据源外部传入
class KSSingleSelectUtil<T>: UITableViewController,UISearchBarDelegate {
    
    
    static func initWithNav(title:String,backColor:UIColor = .black,allArr:[nameAndModel<T>],backClosure:@escaping ((nameAndModel<T>)->()),beforeBackHandle:((nameAndModel<T>)->(Bool))? = nil,selectType:KSSelectType = .unNeedConfirm) -> UIViewController {
        
        let nav = BaseNavigationController()
        let vc = KSSingleSelectUtil(title: title,backColor:backColor, allArr: allArr, backClosure: backClosure,beforeBackHandle: beforeBackHandle,selectType: selectType)
        nav.viewControllers = [vc]
        return nav
    }
    static func initForPush(title:String,allArr:[nameAndModel<T>],backClosure:@escaping ((nameAndModel<T>)->()),beforeBackHandle:((nameAndModel<T>)->(Bool))? = nil,selectType:KSSelectType = .unNeedConfirm) -> UIViewController {
        
        let vc = KSSingleSelectUtil(title: title, allArr: allArr, backClosure: backClosure,beforeBackHandle: beforeBackHandle,selectType: selectType)
        return vc
    }
    
    var backColor:UIColor = .black
    var allArr:[nameAndModel<T>]
    var backClosure:(nameAndModel<T>)->()
    /// 返回之前需要逻辑判断处理  , 给用户一个对象，用户逻辑判断返回是否继续
    var beforeBackHandle:((nameAndModel<T>)->(Bool))?
    var selectType:KSSelectType?
    private var keyWord = ""
    private var searchBar:UISearchBar!
    private var tempArr = [nameAndModel<T>]()
 
    init(title:String,backColor:UIColor = .black,allArr:[nameAndModel<T>],backClosure:@escaping ((nameAndModel<T>)->()),beforeBackHandle:((nameAndModel<T>)->(Bool))?,selectType:KSSelectType = .unNeedConfirm) {
        self.allArr = allArr
        self.backColor = backColor
        self.backClosure = backClosure
        self.beforeBackHandle = beforeBackHandle
        self.selectType = selectType
         super.init(nibName: nil, bundle: nil)
        self.title = title
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let leftbtn = UIButton.creat4Item(title: "返回",color:self.backColor) { _ in
            self.closeAction()
        }
        let left = UIBarButtonItem(customView:leftbtn)
        
        self.navigationItem.leftBarButtonItem = left
        
        self.tableView.estimatedRowHeight = 100
        self.tableView.rowHeight = UITableView.automaticDimension
        let sbg = UIView(frame:CGRect(x:0,y:0,width:KSGlobal.screenW,height:50))
        sbg.backgroundColor = .clear
        searchBar = UISearchBar(frame:CGRect(x:0,y:5,width:KSGlobal.screenW,height:40))
        searchBar.inputAccessoryView = KSToolbar(controller: self)
        searchBar.placeholder = "请输入关键字搜索"
        searchBar.delegate = self
        searchBar.backgroundColor = .clear
        searchBar.backgroundImage = UIImage()
        sbg.addSubview(searchBar)
        tableView.register(GlobalTableViewCell.self, forCellReuseIdentifier: GlobalTableViewCell.identifier)
         tableView.backgroundColor = Theme.awModuleBgColor
        tableView.tableHeaderView = sbg
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.tableFooterView = UIView()
 
        self.filterData()
        
    }
    
    func closeAction() {
        if self.navigationController!.viewControllers.count > 1 { // 说明是push过来的
            self.navigationController?.popViewController(animated: true)
        } else {
            self.dismiss(animated: true, completion: {
            })
        }
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return tempArr.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: GlobalTableViewCell.identifier, for: indexPath) as!
        GlobalTableViewCell
        
        let shows = tempArr[indexPath.row].shows
        
        
        var contentArr:[(String,String)]!
        switch shows.count {
        case 1:
            contentArr = [("",shows[0])]
        case 2:
            contentArr = [(shows[0],shows[1])]
        case 3:
            contentArr = [(shows[0],shows[1]),("",shows[2])]
        case 4:
            contentArr = [(shows[0],shows[1]),(shows[2],shows[3])]
        case 5:
            contentArr = [(shows[0],shows[1]),(shows[2],shows[3]),("",shows[4])]
        case 6:
            contentArr = [(shows[0],shows[1]),(shows[2],shows[3]),(shows[4],shows[5])]
        case 7:
            contentArr = [(shows[0],shows[1]),(shows[2],shows[3]),(shows[4],shows[5]),("",shows[6])]
        case 8:
            contentArr = [(shows[0],shows[1]),(shows[2],shows[3]),(shows[4],shows[5]),(shows[6],shows[7])]
        case 9:
            contentArr = [(shows[0],shows[1]),(shows[2],shows[3]),(shows[4],shows[5]),(shows[6],shows[7]),("",shows[8])]
        case 10:
            contentArr = [(shows[0],shows[1]),(shows[2],shows[3]),(shows[4],shows[5]),(shows[6],shows[7]),(shows[8],shows[9])]
        case 11:
            contentArr = [(shows[0],shows[1]),(shows[2],shows[3]),(shows[4],shows[5]),(shows[6],shows[7]),(shows[8],shows[9]),("",shows[10])]
        case 12:
            contentArr = [(shows[0],shows[1]),(shows[2],shows[3]),(shows[4],shows[5]),(shows[6],shows[7]),(shows[8],shows[9]),(shows[10],shows[11])]
        case 13:
            contentArr = [(shows[0],shows[1]),(shows[2],shows[3]),(shows[4],shows[5]),(shows[6],shows[7]),(shows[8],shows[9]),(shows[10],shows[11]),("",shows[12])]
        case 14:
            contentArr = [(shows[0],shows[1]),(shows[2],shows[3]),(shows[4],shows[5]),(shows[6],shows[7]),(shows[8],shows[9]),(shows[10],shows[11]),(shows[12],shows[13])]
        default:
            contentArr = [("超","out of index")]
        }
  
         cell.setDataSource(contentArr: contentArr)
        
         
        if self.selectType! == .onlyShow {
            cell.selectionStyle = .none
        } else {
            cell.selectionStyle = .default
        }
        
        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let bbHandle = self.beforeBackHandle {
            let flag =  bbHandle(tempArr[indexPath.row])
            if flag {
                self.comfirmAction(indexP:indexPath)
            }
        } else {
            if self.selectType! == .needConfirm {
                let str = tempArr[indexPath.row].shows.joined(separator: "\n")
                alertUtil(self, title: "确认选择：\(str)", operateS: [nameAction(name: "确定", action: { (_) in
                    self.comfirmAction(indexP:indexPath)
                })])
            } else if self.selectType! == .unNeedConfirm {
                self.comfirmAction(indexP:indexPath)
            } else {
                
            }
        }
        
        
    }
    
    func comfirmAction(indexP:IndexPath) {
        if  tempArr.count > indexP.row {
            self.backClosure(tempArr[indexP.row])
        }
         self.closeAction()
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        keyWord = searchText
        self.filterData()
    }
    
    func filterData() {
        
        tempArr.removeAll()
        if keyWord != "" {
            print(keyWord)
            
            
            self.allArr.forEach {
                let str = $0.shows.joined(separator: ",")
                if str.contains(keyWord) {
                    tempArr.append($0)
                }
            }
        } else {
            tempArr = self.allArr
        }
        
        
        self.tableView.reloadData()
    }
    
    
    
}
enum KSSingSSeaType {
    case none,bar,barAndScan // 无   搜索框   框和扫码
}

// 网络外置的选择控件
class KSSingleSelectNetUtil: UITableViewController,UISearchBarDelegate {
    
    var allArr = [Any]()
    var backClosure:((Any)->())?
    var selectType:KSSelectType?
    private var keyWord = ""
    private var searchBar:UISearchBar!
    var page = 1
    var size = KSGlobal.pageSize // size 等于0 认为不分页
    // 网络通过外部注入  page  和  keyword
    var kSSingleSelectNetNetwork:((Int,Int,String)->())?
    // cell 展示外部注入
    var kSSingleSelectNetShowCell:((GlobalTableViewCell,Any)->())?
    /// 返回之前需要逻辑判断处理  , 给用户一个对象，用户逻辑判断返回是否继续
    var beforeBackHandle:((Any)->(Bool))?
    var searchType:KSSingSSeaType = .barAndScan
    var searchPlaceholer = ""
    var tintColor = UIColor.black
//    init(searchPlaceholer:String = "搜索",showSearch:Bool = true,tintColor:UIColor = .black) {
//        
//        self.searchPlaceholer = searchPlaceholer
//        self.tintColor = tintColor
//        self.searchType = showSearch ? .barAndScan : .none
//        super.init(nibName: nil, bundle: nil)
//    }
    init(searchPlaceholer:String = "搜索",searchType:KSSingSSeaType = .barAndScan,tintColor:UIColor = .black) {
        
        self.searchPlaceholer = searchPlaceholer
        self.tintColor = tintColor
        self.searchType = searchType
        super.init(nibName: nil, bundle: nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.estimatedRowHeight = 100
        self.tableView.rowHeight = UITableView.automaticDimension
        let leftbtn = UIButton.creat4Item(title: "返回",color:tintColor) { _ in
            self.closeAction()
        }
        let left = UIBarButtonItem(customView:leftbtn)
        
        self.navigationItem.leftBarButtonItem = left
         
        if self.searchType == .barAndScan {
            addSearchBar()
            addScan()
         } else if self.searchType == .bar {
            addSearchBar()
         }
        
        
        tableView.register(GlobalTableViewCell.self, forCellReuseIdentifier: GlobalTableViewCell.identifier)
        tableView.tableFooterView = UIView()
        tableView.backgroundColor = Theme.awModuleBgColor
        tableView.showsVerticalScrollIndicator = false

        tableView.separatorStyle = .none
        
        
        self.tableView.mj_header = KSRefreshHeader {
            self.page = 1
            self.network(page:self.page,size:self.size,keyWord:self.keyWord)
        }
        if size != 0 {
            self.tableView.mj_footer = KSRefreshFooter {
                self.page += 1
                self.network(page:self.page,size:self.size,keyWord:self.keyWord)
            }
        }
        
        self.tableView.mj_header?.beginRefreshing()
        
    }
    func addSearchBar() {
        searchBar = UISearchBar(frame:CGRect(x:0,y:0,width:KSGlobal.screenW,height:40))
        searchBar.inputAccessoryView = KSToolbar(controller: self)
        searchBar.placeholder = self.searchPlaceholer
        searchBar.backgroundImage = UIImage()
        searchBar.delegate = self
        tableView.tableHeaderView = searchBar
    }
    func addScan() {
        let rightbtn = UIButton.creat4Item(title: "扫码",color:tintColor) { _ in
             SwiftScanHelper.shared.openScan(controller:self) { rst in
                self.searchBar.text = rst
                self.keyWord = self.searchBar.text.unwrap
                self.tableView.mj_header?.beginRefreshing()
             }
         }
        let right = UIBarButtonItem(customView:rightbtn)
        self.navigationItem.rightBarButtonItem = right
    }
  
    func showData(arr:[Any]) {
        self.allArr += arr
        self.tableView.reloadData()
        self.tableView.mj_header?.endRefreshing()
        if arr.count < size {
            self.tableView.mj_footer?.endRefreshingWithNoMoreData()
        } else {
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
    
    func network(page:Int,size:Int,keyWord:String) {
        if let clo = kSSingleSelectNetNetwork {
            clo(page,size,keyWord)
        }
    }
    
    func closeAction() {
        if self.navigationController!.viewControllers.count > 1 { // 说明是push过来的
            self.navigationController?.popViewController(animated: true)
        } else {
            self.dismiss(animated: true, completion: {
            })
        }
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return allArr.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        
        let cell = tableView.dequeueReusableCell(withIdentifier: GlobalTableViewCell.identifier, for: indexPath) as!
        GlobalTableViewCell
        
        if let clo = kSSingleSelectNetShowCell {
            clo(cell,self.allArr[indexPath.row])
        }
        
        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
        if let bbHandle = self.beforeBackHandle {
            let flag =  bbHandle(self.allArr[indexPath.row])
            if flag {
                if let clo = backClosure {
                    clo(self.allArr[indexPath.row])
                    self.closeAction()
                }
            }
        } else {
            if let clo = backClosure {
                clo(self.allArr[indexPath.row])
                self.closeAction()
            }
        }
        
        
        
        
        
        
        
    }
    
    func comfirmAction(indexP:IndexPath) {
        
        self.closeAction()
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        keyWord = searchBar.text.unwrap
        self.tableView.mj_header?.beginRefreshing()
        
    }
    
    //searchBar编辑
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        keyWord = searchBar.text.unwrap
        self.tableView.mj_header?.beginRefreshing()
        
    }
    
}
struct KVArrayUtil {
    // 0 是key   1 是  value
    var arr = [(String,String)]()
    func getK(v:String?) -> String {
        if let index = arr.getIndexFor({ model in
            return model.1 == v
        }) {
            return arr[index].0
        } else {
            return ""
        }
    }
    func getV(k:String?) -> String {
        if let index = arr.getIndexFor({ model in
            return model.0 == k
        }) {
            return arr[index].1
        } else {
            return ""
        }
    }
    
}

 
